package JDK91011;

import org.junit.jupiter.api.Test;

import javax.swing.text.html.Option;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Optional;
import java.util.function.Consumer;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-08 22:48
 * @description Java11新特性1：String中新增的方法
 */
public class Java11Test {

    @Test
    public void test1(){
        //isBlank:
        System.out.println(" \t \n    ".isBlank());
        System.out.println("     ".isEmpty());

        //strip():去除首尾空白
        System.out.println("------"+"\t  abc \n".strip()+"------");

        //stripTrailing():去除尾部空白
        //stripLeading():去除首部空白

        //repeat(int count)
        String str1="abc";
        String str2=str1.repeat(5);
        System.out.println(str2);

        //lines().count
        String str3="ahd\ndada\ndadas";
        System.out.println(str3.lines().count());
    }

    //java11特性二：Optional新增的方法
    @Test
    public void test2(){
        Optional<Object> op=Optional.empty();
        System.out.println(op.isPresent());//判断内部的value是否存在
        System.out.println(op.isEmpty());//判断内部的value是否为空

        //roElseThrow():value非空，返回value；否则抛异常 NoSuchElementException
        op=Optional.of("abc");
        Object obj=op.orElseThrow();
        System.out.println(obj);

        //op=Optional.empty();
        //or value非空，返回对应的optional，value为空，返回形参封装的Optional
        Optional<String> op1 = Optional.of("hello");
        Optional<Object> or = op.or(() -> op1);
        System.out.println(or);
    }

    //java11新特性三：局部变量类型推断的升级
    @Test
    public void test3(){
        //错误的形式：必须要求类型，可以加上var
        //Consumer<String> con1=(@Deprecated t)-> System.out.println(t.toUpperCase());

        //正确的形式：
        //使用var的好处是在使用Lambda表达式时给参数加上注解
        Consumer<String> con2=(@Deprecated var t)-> System.out.println(t.toUpperCase());

    }
    //java11新特性四：HttpClient替换原有的HttpURLConnection
    @Test
    public void test4(){
        HttpClient client= HttpClient.newHttpClient();
        HttpRequest request=HttpRequest.newBuilder(URI.create("http://127.0.0.1:8080/test")).build();
        HttpResponse.BodyHandler<String> requestBodyHandler= HttpResponse.BodyHandlers.ofString();
        HttpResponse<String> response= null;
        try {
            response = client.send(request,requestBodyHandler);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String body=response.body();
        System.out.println(body);
    }

}
